import {Injectable} from '@angular/core';
import {Http, RequestOptions, Headers, Jsonp, Response, RequestOptionsArgs, URLSearchParams} from '@angular/http';
import {OauthService} from './oauth.service';


@Injectable()
export class HttpService {

  r = {
    protocol: /([^\/]+:)\/\/(.*)/i,
    host: /(^[^\:\/]+)((?:\/|:|$)?.*)/,
    port: /\:?([^\/]*)(\/?.*)/,
    pathname: /([^\?#]+)(\??[^#]*)(#?.*)/
  };

  constructor(private http: Http, private jsonp: Jsonp, private  oauthService: OauthService) {

  }

  parseUrl(url) {
    let tmp, res = {};
    res['href'] = url;
    for (const p in this.r) {
      tmp = this.r[p].exec(url);
      res[p] = tmp[1];
      url = tmp[2];
      if (url === '') {
        url = '/';
      }
      if (p === 'pathname') {
        res['pathname'] = tmp[1];
        res['search'] = tmp[2];
        res['hash'] = tmp[3];
      }
    }
    console.log(url);
    return res;
  };

  // get方法
  httpGet(url: string, options?: RequestOptionsArgs) {
    if (!options) {
      options = new RequestOptions({});
    }
    if (!options.headers) {
      this.setDefaultHeader(options);
    }
    // const headers = new Headers();
    return this.http.get(url, options).map(res => res.json());
  }


  // get方法 oauth
  httpGetAuth(url: string, options?: RequestOptionsArgs) {
    if (!options) {
      options = new RequestOptions({});
    }
    if (!options.headers) {
      this.setDefaultHeader(options);
    }
    const token = this.oauthService.getAccessToken();
    if (token) {
      options.headers.append('Authorization', 'Bearer ' + token);
      // options.headers.append('x-xsrf-token',token);
    }
    const nowApplet = JSON.parse(localStorage.getItem('nowApplet'));
    if (nowApplet) {
      const userInfo = JSON.parse(localStorage.getItem('userInfo'));
      if (userInfo) {
        const applet_uuid = nowApplet.applet_uuid;
        const params = new URLSearchParams();
        params.set('applet_uuid', applet_uuid);
        options.params = params;
      }
    }
    return this.http.get(url, options).map(res => res.json());
  }

  // httpGetWithJWT(url: string, data:any) {
  //     let token = localStorage.getItem('token');
  //     let params = new URLSearchParams();
  //     for(let key in data) {
  //         params.set(key.toString(), data[key]);
  //     }
  //     //params.set('token',token.access_token);
  //
  //     return this.http.get(url, params).map(res => res.json());
  // }

  httpPut(url: string, options?: RequestOptionsArgs) {
    if (!options) {
      options = new RequestOptions({});
    }
    if (!options.headers) {
      this.setDefaultHeader(options);
    }
    return this.http.put(url, options).map(res => res.json());
  }

  httpPutAuth(url: string, options?: RequestOptionsArgs) {
    if (!options) {
      options = new RequestOptions({});
    }
    if (!options.headers) {
      this.setDefaultHeader(options);
    }
    const token = this.oauthService.getAccessToken();
    if (token) {
      options.headers.append('Authorization', 'Bearer ' + token);
    }
    return this.http.put(url, options).map(res => res.json());
  }

  httpDelete(url: string, options?: RequestOptionsArgs) {
    if (!options) {
      options = new RequestOptions({});
    }
    if (!options.headers) {
      this.setDefaultHeader(options);
    }
    return this.http.delete(url, options).map(res => res.json());
  }

  httpDeleteAuth(url: string, options?: RequestOptionsArgs) {
    if (!options) {
      options = new RequestOptions({});
    }
    if (!options.headers) {
      this.setDefaultHeader(options);
    }
    const token = this.oauthService.getAccessToken();
    if (token) {
      options.headers.append('Authorization', 'Bearer ' + token);
    }
    return this.http.delete(url, options).map(res => res.json());
  }

  // post 方法
  httpPost(url: string, body: any, options?: RequestOptionsArgs) {
    if (!options) {
      options = new RequestOptions({});
    }
    if (!options.headers) {
      this.setDefaultHeader(options);
    }
    return this.http.post(url, body, options).map(res => res.json());
  }


  // post 方法 oauth
  httpPostAuth(url: string, body: any, options?: RequestOptionsArgs) {
    if (!options) {
      options = new RequestOptions({});
    }
    if (!options.headers) {
      this.setDefaultHeader(options);
    }
    const token = this.oauthService.getAccessToken();
    if (token) {
      options.headers.append('Authorization', 'Bearer ' + token);
    }
    const nowApplet = JSON.parse(localStorage.getItem('nowApplet'));
    if (nowApplet) {
      const userInfo = JSON.parse(localStorage.getItem('userInfo'));
      if (userInfo) {
        const params = new URLSearchParams();
        params.append("auth_sign", nowApplet.auth_sign);
        params.append("auth_applet_member_id", nowApplet.auth_applet_member_id);
        params.append("auth_expire_at", nowApplet.auth_expire_at);
        options.params = params;
      }
    }
    return this.http.post(url, body, options).map(res => res.json());
  }

  httpPostAuth1(url: string, body: any, options?: RequestOptionsArgs) {
    if (!options) {
      options = new RequestOptions({});
    }
    if (!options.headers) {
      this.setDefaultHeader(options);
    }
    const token = this.oauthService.getAccessToken();
    if (token) {
      options.headers.append('Authorization', 'Bearer ' + token);
    }
    /*if (token) {
     options.headers.append('Authorization', 'Bearer ' + token.auth.original.access_token);
     }*/
    return this.http.post(url, body, options).map(res => res);
  }

  // jsonp跨域请求
  jsonpGet(url: string, options?: RequestOptionsArgs) {
    if (!options) {
      options = new RequestOptions({});
    }
    if (!options.headers) {
      this.setDefaultHeader(options);
    }
    return this.jsonp.get(url, options).map(res => res.json());
  }

  // 错误处理
  handleError(error: Response) {
    console.error(error);
    // return Observable.throw(error.json().error || 'Server error');
  }

  private setDefaultHeader(options) {
    options.headers = new Headers({
      // 'Content-Type': 'application/x-www-form-urlencoded',
      'Accept': 'application/json',
    });
  }


  catchAuthError(self: HttpService) {
    /*return (res: Response) => {
     console.log(res);
     if (res.status === 401 || res.status === 403) {
     // if not authenticated
     console.log(res);
     }
     };*/
  }
}
